<script setup lang="ts">
import { getCurrentInstance, reactive, nextTick } from 'vue'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const crop = reactive({
  show: false,
  cropper: null,
  // ----
  toBase64: true,
  source: '',
  option: {},
  cropImg: {},
  callback: '',
  yes: '',
  no: ''
})

/* ---- */
const open = (opt) => {
  if (opt) {
    for (var key in opt) { crop[key] = opt[key] }
    crop.show = true
  }
  nextTick(() => {
    crop.cropper = new Cropper(proxy.$refs.cutImg, crop.option)
  })
  crop.callback && crop.callback()
}
const finish = () => {
  const result = crop.cropper.getCroppedCanvas(crop.cropImg.true)
  if (crop.toBase64) {
    // --画布转base64格式--
    const imgBackInfo = {
      url: result.toDataURL(crop.cropImg.type, crop.cropImg.scale),
      info: {
        W: result.width,
        H: result.height
      }
    }
    crop.yes && crop.yes(imgBackInfo)
    close()
  } else {
    // --画布转blob格式--
    result.toBlob((blob) => {
      const imgBackInfo = {
        url: window.URL.createObjectURL(blob),
        info: {
          W: result.width,
          H: result.height
        }
      }
      crop.yes && crop.yes(imgBackInfo)
      close()
    }, crop.cropImg.type, crop.cropImg.scale)
  }
}
const cancel = () => {
  crop.no && crop.no()
  close()
}
const close = () => {
  crop.cropper.destroy()
  crop.show = false
  crop.cropper = null
  // ----
  crop.source = ''
  crop.option = {}
  crop.cropImg = {}
  crop.callback = ''
  crop.yes = ''
  crop.no = ''
}

/* ---- */
defineExpose({
  open
})
</script>

<template>
  <transition name="fade">
    <div class="cutBox" v-if="crop.show">
      <img ref="cutImg" :src="crop.source" style="display: none;" />
      <div class="cutBox-top">
        <span class="fal fa-times xw-right" @click="cancel"></span>
      </div>
      <div class="cutBox-foot xw-flex xw-flex-align xw-flex-justify">
        <span @click="cancel">取消</span>
        <span @click="finish">完成</span>
      </div>
    </div>
  </transition>
</template>

<style scoped>
/* ---- */
.cutBox { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); z-index: 999; }
.cutBox-top { position: fixed; top: 0; left: 0; right: 0; height: 5rem; color: #ffffff; background: rgba(0, 0, 0, 0.7); }
.cutBox-top span { width: 5rem; height: 5rem; line-height: 5rem; text-align: center; font-size: 2.4rem; }
.cutBox-top span:active { background: rgba(255, 255, 255, 0.2); }
.cutBox-foot { position: fixed; bottom: 0; left: 0; right: 0; height: 5rem; color: #ffffff; background: rgba(0, 0, 0, 0.7); }
.cutBox-foot span { padding: 0 1.4rem; height: 5rem; line-height: 5rem; font-size: 1.6rem; }
.cutBox-foot span:active { background: rgba(255, 255, 255, 0.2); }
</style>
